package com.example.academic_affairs_system.utils;

import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.Objects;

/**
 * 公共工具类
 *
 * @author hjx
 * @since 2023/02/01 12:00 AM
 */
public class CommonUtils {
  /**
   * 写出 json
   *
   * @param response 响应
   * @param data 写出数据
   */
  public static void writeJson(HttpServletResponse response, Object data) {
    response.setContentType("application/json;charset=UTF-8");
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Method", "*");
    PrintWriter out = null;
    try {
      out = response.getWriter();
      out.write((new ObjectMapper()).writeValueAsString(data));
    } catch (IOException var8) {
      var8.printStackTrace();
    } finally {
      if (Objects.nonNull(out)) {
        out.flush();
        out.close();
      }
    }
  }

  public static <T> void writePojo(HttpServletResponse response, T data) {
    Class<?> clazz = data.getClass();
    Field[] fields = clazz.getDeclaredFields();
    JSONObject json = new JSONObject();
    for (Field field : fields) {
      field.setAccessible(true);
      try {
        Object o = field.get(data);
        if (o != null) {
          json.set(field.getName(), o);
        }
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      }
    }
    writeJson(response, json);
  }
}
